#!/usr/bin/python3
#coding=utf-8

import sys
from loggers import get_logger
from control_test import check_pid,check_cpid,stop_pid,start_target,start_control

logger = get_logger(__name__)

def start_test():
    try:
        # 先查看进程是否存在
        result = check_pid()
        result1 = check_cpid()
        if not result[0]:
            pid_tar = start_target()
            logger.info('进程已经启动，当前的进程号为%s' % pid_tar)
            if not result1[0]:
                pid = start_control()
                if pid:
                    logger.info('监听脚本启动成功，进程号%s' % str(pid))
            else:
                logger.info('监听已经启动，不能重复启动！')
        else:
            logger.info('进程已经启动，当前的进程号为%s'%result[1])
    except Exception as e:
        logger.error(e)

# 当输出被重定向后，stdout为空

def stop_test():
    try:
        # 检查监听是否存在，存在则杀死
        result_cpid = check_cpid()
        if result_cpid[0]:
            # 杀死监听程序
            stop_pid(result_cpid[1])
            logger.info('成功杀死监听进程%s！'%result_cpid[1])
        else:
            logger.info('监听进程不存在，不需要停止！')

        result_pid = check_pid()
        if result_pid[0]:
            # 杀死目标进程
            stop_pid(result_pid[1])
            logger.info('成功杀死目标进程%s！' % result_pid[1])
        else:
            logger.info('目标进程不存在，不需要停止！')
    except Exception as e:
        logger.error(e)

def restart_test():
    '''
    检测目标进程是否存在，存在则杀死并重启，不存在则启动
    :return:
    '''
    result_pid = check_pid()
    if result_pid[0]:
        # 杀死目标进程
        stop_pid(result_pid[1])
        pid = start_target()
        if pid:
            logger.info('目标进程%s启动成功！'% pid)
    else:
        pid = start_target()
        if pid:
            logger.info('目标进程%s启动成功！' % pid)

if __name__ == '__main__':
    list1 = sys.argv
    if len(list1) == 1:
        print('you must to give a params!for example "start" or "stop" or "restart"')
    elif len(list1) > 2:
        print('The commend need one params,but more params to give!')
    else:
        if list1[1] == 'start':
            start_test()
        elif list1[1] == 'stop':
            stop_test()
        elif list1[1] == 'restart':
            restart_test()
        else:
            print('you must to input the one of start,stop or restart')